package cn.schoolwow.util.module.crypto.cipher.aes.flow;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.module.crypto.cipher.aes.domain.AESCipherOption;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AESDecryptFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        AESCipherOption aesCipherOption = flowContext.checkInstanceData(AESCipherOption.class);
        Cipher cipher = flowContext.checkInstanceData(Cipher.class);
        SecretKeySpec keySpec = flowContext.checkInstanceData(SecretKeySpec.class);

        if(null==aesCipherOption.data||aesCipherOption.data.isEmpty()){
            flowContext.broken("密文内容为空");
        }

        if(null==aesCipherOption.iv){
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
        }else{
            byte[] ivBytes = Base64.getDecoder().decode(aesCipherOption.iv);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes,0,16);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivParameterSpec);
        }
        byte[] decoded = Base64.getDecoder().decode(aesCipherOption.data);
        byte[] decrypted = cipher.doFinal(decoded);
        String plainText = new String(decrypted, StandardCharsets.UTF_8);
        flowContext.putReturnData("string", plainText);
    }

    @Override
    public String name() {
        return "AES解密";
    }

}
